//JavaScript Framework 2.0 Code
try {
	Type.registerNamespace('com.yonyou.ncmm_pac_pda.MaterialOutScanController');
	com.yonyou.ncmm_pac_pda.MaterialOutScanController = function() {
		com.yonyou.ncmm_pac_pda.MaterialOutScanController.initializeBase(this);
		this.initialize();
	}

	//是否需要确认批次号变更
	//下列情况发生时，要把g_bNeedConfirm置为true：
	//		扫码操作
	//		手工修改批次号
	var g_bNeedConfirm = true;

	function com$yonyou$ncmm_pac_pda$MaterialOutScanController$initialize() {

	}

	function com$yonyou$ncmm_pac_pda$MaterialOutScanController$evaljs(js) {
		eval(js)
	}

	//返回按钮单击事件
	function back(sender, args) {
		$view.close();
	}

	//右上角公共菜单
	function loadmenu(sender, args) {
		NCMMPubMenu.openDropDownList("imagebutton1", true);
	}

	//公共菜单-扫描记录按钮单击事件
	function showScanList() {
		$view.open({
			"viewid": "com.yonyou.ncmm_pac_pda.MaterialOutScanList", //目标页面（首字母大写）全名
			"isKeep": "false"
		});
	}

	//页面数据加载事件
	function com$yonyou$ncmm_pac_pda$MaterialOutScanController$load(sender, args) {
		var code = $param.getString("vbillcode");
		if(code != null && code != "") {
			// 扫描的是单据码
			$id("textbox1").set("value", code);
			$ctx.dataBind();
		}
		//row=materialoutvo行数据
		var param = $param.getJSONObject("row");
		//		$alert("param row="+$jsonToString(row));
		if (param != null) {
		
		var row = param["data"];
		var type = param["type"];
		var jsonrow = {};
		if(type && (type == "1" || type == 1)) { //扫单据码或采集跳转过来的
			//不要把单据行上的扫描主辅数量带过来
			var queryvos = NCMMDBUtil.getVOsByBillcodeRow(MaterialOutVO, MaterialOutVO.VBILLCODE.name, row[MaterialOutVO.VBILLCODE.name], MaterialOutVO.CROWNO.name, row[MaterialOutVO.CROWNO.name]);
			if(queryvos) {
				jsonrow = queryvos[0];
			}
			jsonrow = NCMMPubUtil.htmlspecialjson2UI(jsonrow);
			jsonrow[MaterialOutVO.SCANNUM.name] = "";
			jsonrow[MaterialOutVO.SCANASSISTNUM.name] = "";
		} else { //扫描记录修改
			var queryvos = NCMMDBUtil.getVOsByBillcodeRow(MaterialOutScansVO, MaterialOutScansVO.VBILLCODE.name, row[MaterialOutScansVO.VBILLCODE.name], MaterialOutScansVO.CROWNO.name, row[MaterialOutScansVO.CROWNO.name]);
			if(queryvos) {
				jsonrow = queryvos[0];
			}
			jsonrow = NCMMPubUtil.htmlspecialjson2UI(jsonrow);
			//根据扫描记录的ts得到rowid
			var tablerowid = NCMMMOUtil.getRowidByTS(row["scants"]);
			jsonrow["tablerowid"] = tablerowid;
		}

		$ctx.push(jsonrow);
		}
	}

	//扫描数量控件onInput事件
	function onScannumInput(sender, args) {
		$ctx.dataCollect();
		showScannum($ctx.getString("scannum"), 1);
	}

	//扫描辅数量控件onInput事件
	function onScanassistnumInput(sender, args) {
		$ctx.dataCollect();
		showScannum($ctx.getString("scanassistnum"), 0);
	}

	//主辅扫描数量变化同步
	//num - 变化数值
	//direction - 同步方向， 1- 主数量变化，同步辅数量； 0-辅数量变化，同步主数量
	function showScannum(num, direction) {
		if(num == "" || (num.length == 1 && num == "-")) {
			$ctx.put("scannum", num);
			$ctx.put("scanassistnum", num);
			$ctx.dataBind();
			return;
		}

		var checknum;
		if(num.charAt(num.length - 1) == ".") {
			checknum = num.substring(0, num.length - 1);
		} else {
			checknum = num;
		}

		var reg1 = /^\d+(\.\d+)?$/; //非负浮点数（正浮点数+0）
		var reg2 = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数

		if(!reg1.test(checknum) && !reg2.test(checknum)) {
			$toast("请输入数字！");
			num = num.substring(0, num.length - 1);
			if(direction == 1) {
				$ctx.put("scannum", num);
				$ctx.dataBind();
			} else {
				$ctx.put("scanassistnum", num);
				$ctx.dataBind();
			}
			return;
		}

		checknum = parseFloat(checknum);
		var num2 = numExchange(checknum, direction, $ctx.getString("vchangerate"));
		if(num.charAt(num.length - 1) == ".") {
			num2 = String(num2) + ".";
		}
		if(direction == 1) {
			$ctx.put("scannum", num);
			$ctx.put("scanassistnum", num2);
		} else {
			$ctx.put("scannum", num2);
			$ctx.put("scanassistnum", num);
		}
		$ctx.dataBind();
	}

	function checkIllegal(strnum) {
		var isLegal = true;

		for(var i = 0; i < strnum.length; i++) {
			var chr = strnum.charAt(i);
			if(chr == "-" && i != 0) {
				isLegal == false;
				break;
			}
			if(chr == "." && i == 0) {
				isLegal == false;
				break;
			}
			if(chr == "." && i != strnum.indexOf(".")) {
				isLegal == false;
				break;
			}
			var anum = parseInt(chr);
			if(anum == null || anum == NaN) {
				isLegal == false;
				break;
			}
		}

		return isLegal;
	}

	//扫码文本框的onchange事件
	function onScantxtInput(sender, args) {
		afterScanCode(); //手工录入条码
		$id("textbox0").focus();
	}
	//扫码按钮单击事件
	function com$yonyou$ncmm_pac_pda$MaterialOutScanController$imagebutton0_onclick(sender, args) {
		$scanner.open({
			bindfield: "scancode",
			callback: "afterScanCode()" //扫码结束后的处理事件
		});
	}

	//扫码结束后的处理事件（摄像头扫码、红外扫码、手工输入条码）
	//将条码内容（字符串）置于code控件中
	function afterScanCode() {
		// 获取到扫码结果
		var scanresult = $ctx.getString("scancode");
		//		$toast(scanresult);
		//根据条码规则解析出物料编码、批次号、序列号
		var scaninfo = parsebarcode(scanresult);
		if(scaninfo == null || scaninfo[MaterialOutScansVO.CINVCODE.name] == null || scaninfo[MaterialOutScansVO.CINVCODE.name] == "") {
			if(scaninfo["failmsg"] && scaninfo["failmsg"] != "")
				$alert(scaninfo["failmsg"]);
			else
				$alert("物料码解析失败，请重新录入条码。");

			$ctx.put("scancode", "");
			$ctx.dataBind();
			return;
		}
		g_bNeedConfirm = true;
		//<1>根据单据号(来自ctx)、物料编码(来自条码解析)、物料批次号(可选，来自条码解析)匹配出上游单据单据行
		var outvo = matchSingleOutVO($ctx.getString("vbillcode"), scaninfo[MaterialOutScansVO.CINVCODE.name], scaninfo[MaterialOutScansVO.VBATCHCODE.name]);
		//没有匹配出单据行，则返回
		if(outvo == null) {
			return;
		}
//		$alert("outvo=" + $jsonToString(outvo));
		scaninfo["scannum"] = "1";
		if(scaninfo["vbatchcode"] != outvo[MaterialOutVO.VBATCHCODE.name]) {
			if(outvo[MaterialOutVO.VBATCHCODE.name] == "")
				scaninfo["vnotebody"] = "批次号变更为" + scaninfo["vbatchcode"];
			else
				scaninfo["vnotebody"] = "原批次号" + outvo[MaterialOutVO.VBATCHCODE.name] + "变更为" + scaninfo["vbatchcode"];
		}
		//更新界面显示及本地数据库表(新增扫描表记录，rowid为null)
		doUpdate(outvo, scaninfo, null);
	}

	//保存按钮单击事件
	//isautosave - 区分保存按钮触发操作和提交事件中的自动保存
	function localSave(sender, args, isautosave) {
		if(isautosave == null)
			isautosave = false;

		$ctx.dataCollect();
		var ctxData = $ctx.getJSONObject();
//		$alert("ctxData1 = " + $jsonToString(ctxData));
		ctxData = NCMMPubUtil.htmlspecialjson2UI(ctxData);
//		$alert("ctxData2 = " + $jsonToString(ctxData));

		//如果物料码为空，则不能保存，给出提示
		if(ctxData["cinvcode"] == null || ctxData["cinvcode"] == "") {
			if(isautosave)
				$alert("没有物料信息，不能提交。");
			else
				$alert("没有物料信息，不能保存。");
			return false;
		}
		//如果扫描数量为空，则不能保存，给出提示
		if((ctxData["scannum"] == null || ctxData["scannum"] == "") || (ctxData["scanassistnum"] == null || ctxData["scanassistnum"] == "")) {
			if(isautosave)
				$alert("请先输入扫描数量后再提交。");
			else
				$alert("请先输入扫描数量后再保存。");
			return false;
		}

		var outvo = NCMMMOUtil.getOriginalOutvo(ctxData["vbillcode"], ctxData["crowno"]);

		//如果出现批次变更的情况，保存前先确认批次号变更
		var orgbatchcode = outvo[MaterialOutVO.VBATCHCODE.name];
		var newbatchcode = ctxData["vbatchcode"];
		var vnotebody = "";
		if(orgbatchcode != newbatchcode) {
			if(orgbatchcode == "")
				vnotebody = "批次号变更为" + newbatchcode;
			else {
				vnotebody = "原批次号" + orgbatchcode + "变更为" + newbatchcode;
			}
			if(g_bNeedConfirm) {
				g_bNeedConfirm = false;
				var isChange = isChangeBatchcode(orgbatchcode, newbatchcode);
				//用户取消变更，则取消保存操作
				if(isChange == false) {
					if(isautosave)
						$toast("提交操作取消。");
					else
						$toast("保存操作取消。");
					return false;
				}
			}
		}
		var scaninfo = {
			"cinvcode": ctxData["cinvcode"],
			"vbatchcode": ctxData["vbatchcode"],
			"vserialcode": ctxData["vserialcode"],
			"scannum": ctxData["scannum"],
			"scandate": NCMMPubUtil.getNowDateTime(),
			"scants": NCMMPubUtil.getTS(),
			"vnotebody": vnotebody
		};

		doUpdate(outvo, scaninfo, ctxData["tablerowid"]);
		if(isautosave == false)
			$toast("保存成功");
		return true;
	}

	//经过条码规则解析，解析出物料信息
	/*
	 {	"cinvcode":"xxxx", 	"vbatchcode":"xxxxxxxxxx", 	"vserialcode":"xxxxxxxxx"	 }
	 * */
	function parsebarcode(scancode) {
		//				$alert("scancode=" + scancode);
		var materialinfo = NCMMBarcodeParseUtil.parseMaterialBar(scancode);
		if(materialinfo == null)
			return null;
		//		materialinfo = eval(materialinfo);
//		$alert("materialinfo=" + $jsonToString(materialinfo));
		materialinfo["cinvcode"] = materialinfo["code"];
		//		$alert("materialinfo=" + $jsonToString(materialinfo));

		return materialinfo;
	}

	//<1>根据单据号、物料编码匹配出材料出库单据行
	//如果匹出多行，再用批次号过滤
	//如果还有多行，则再过滤掉扫描数量>=应发的行
	//如果仍然还有多行，则任取一行返回
	function matchSingleOutVO(vbillcode, cinvcode, vbatchcode) {
		//用单据号+物料码匹配上游单据
		var wheresql1 = "where " + MaterialOutVO.VBILLCODE.name + " = '" + NCMMPubUtil.htmlspecialchars2UI(vbillcode) +
			"' and " + MaterialOutVO.CINVCODE.name + " = '" + NCMMPubUtil.htmlspecialchars2UI(cinvcode) + "'";
		var result1 = getMatchVOsByCondition(MaterialOutVO, wheresql1);
		//没匹配到行，说明单据中不包含条码中的物料
		if(result1 == null) {
			$alert("扫描物料" + cinvcode + "不在对应的单据" + vbillcode + "中");
			//清空条形码
		    $id("textbox0").set("value", null);
			return null;
		}

		//如果条码中不包括批次号，则从结果集result1中返回数量差值最大行
		if(vbatchcode == null || vbatchcode == "") {
			//获得result1中（应发-实发）差值最大的行
			var resultvo = getMaxDValue(result1);
			return resultvo;
		}

		//用单据号+物料码+批次号匹配上游单据
		var wheresql2 = wheresql1 + " and " + MaterialOutVO.VBATCHCODE.name + " = '" + NCMMPubUtil.htmlspecialchars2UI(vbatchcode) + "'";
		var result2 = getMatchVOsByCondition(MaterialOutVO, wheresql2);
		//		$alert("result2="+$jsonToString(result2));
		//如果匹配到了，则从结果集result2中返回数量差值最大行
		if(result2 != null) {
			//获得result2中（应发-实发）差值最大的行
			var resultvo = getMaxDValue(result2);
			//			$alert("resultvo="+$jsonToString(resultvo));
			return resultvo;
		}
		//如果没有匹配到，有两种情况，一种是存在批次号为空的物料行
		var wheresql3 = wheresql1 + " and " + MaterialOutVO.VBATCHCODE.name + " = ''";
		var result3 = getMatchVOsByCondition(MaterialOutVO, wheresql3);
		//		$alert("result2="+$jsonToString(result2));
		if(result3 != null) {
			//获得result3中（应发-实发）差值最大的行
			var resultvo = getMaxDValue(result3);
			//			$alert("resultvo="+$jsonToString(resultvo));
			return resultvo;
		}
		//另一种是不存在批次号为空的物料行，即条码的批次号和上游单据行都不匹配
		{
			//获得result1中（应发-实发）差值最大的行
			var resultvo = getMaxDValue(result1);
			//			$alert("resultvo="+$jsonToString(resultvo));
			if(resultvo == null) {
				return resultvo;
			}

			if(g_bNeedConfirm) {
				g_bNeedConfirm = false;
				//询问是否变更批次号
				var isChange = isChangeBatchcode(resultvo[MaterialOutVO.VBATCHCODE.name], vbatchcode);

				if(isChange) {
					return resultvo;
				} else {
					$alert("没有找到匹配的单据行，请重新录入条码。");
					return null;
				}
			} else
				return resultvo;
		}
	}

	//根据查询条件匹配物料行
	function getMatchVOsByCondition(VOClass, wheresql) {
//		$alert("wheresql=" + wheresql);
		var retData = NCMMPubUtil.queryVONoCallback(VOClass, wheresql);
		if(retData == null || (eval(retData)).length == 0) {
			return null;
		}
		retData = NCMMPubUtil.htmlspecialjsonarray2UI(retData);
		return retData;
	}

	//从vos数组中获得（应发-实发）差值最大的行
	function getMaxDValue(vos) {
		var max = 0;
		if(vos.length == 1)
			return vos[max];

		var maxdvalue = NaN;
		for(var i = 0; i < vos.length; i++) {
			var nshouldinnum = 0.0;
			var scannum = 0.0;

			if(vos[i][MaterialOutVO.NSHOULDINNUM.name] && vos[i][MaterialOutVO.NSHOULDINNUM.name] != "")
				nshouldinnum = parseFloat(vos[i][MaterialOutVO.NSHOULDINNUM.name]);
			if(vos[i][MaterialOutVO.SCANNUM.name] && vos[i][MaterialOutVO.SCANNUM.name] != "")
				scannum = parseFloat(vos[i][MaterialOutVO.SCANNUM.name]);

			var dvalue = nshouldinnum - scannum;
			if(i == 0 || dvalue > maxdvalue) {
				maxdvalue = dvalue;
				max = i;
			}
		}

		return vos[max];
	}

	//询问是否变更批次号
	function isChangeBatchcode(orgBatchcode, newBatchcode) {
		var msg = "是否变更单据行批次号【" + orgBatchcode + "】为【" + newBatchcode + "】？";
		return($confirm(msg));
	}

	//更新界面显示及本地数据库表
	//outvo-上游单据行vo；scaninfo-扫描信息； rowid-当前扫描记录rowid
	function doUpdate(outvo, scaninfo, rowid) {
		//<2>更新页面显示
		var newscannum = parseFloat(scaninfo["scannum"]); //扫描主数量
		scaninfo[MaterialOutScansVO.SCANNUM.name] = newscannum;
		//计算辅数量
		var newscanassistnum = numExchange(newscannum, 1, outvo[MaterialOutVO.VCHANGERATE.name]);
		scaninfo[MaterialOutScansVO.SCANASSISTNUM.name] = newscanassistnum;
		//更新界面显示
		//如果条码解析时有解析到批次号/序列号，则把批次号/序列号显示到当前页面里	
		showPage(outvo, scaninfo);
		//		$alert("after showPage");
		//更新本地表记录(上游单据行+扫描记录表), rowid为null表示新增
		updateLocalTableRecord(outvo, scaninfo, rowid);
	}

	//主辅数量互转
	//srcnum: 被转换数值(float)
	//direction:转换方向（1-主转换成辅；0-辅转换成主）
	//changerate：换算率（字符串）
	function numExchange(srcnum, direction, changerate) {
		var tarnum = srcnum;
		if(changerate == null || changerate == "")
			return tarnum;

		var crArray = changerate.split("/");
		if(crArray == null || crArray.length != 2)
			return tarnum;

		var cru = parseFloat(crArray[0]);
		var crd = parseFloat(crArray[1]);
		if(cru == null || crd == null)
			return tarnum;

		if(direction > 0) { //主-->辅
			tarnum = (srcnum * crd) / cru;
		} else {
			tarnum = (srcnum * cru) / crd;
		}

		return tarnum;
	}

	//<2>更新页面显示
	//扫码解析出来的物料编码、批次号、序列号
	//其他信息从单据行数据中补全
	//扫描主辅数量
	function showPage(outvo, scaninfo) {
//				$alert("scaninfo="+$jsonToString(scaninfo));
		var row = outvo;
		if(scaninfo[MaterialOutScansVO.VBATCHCODE.name] != "") {
			row["vbatchcode"] = scaninfo[MaterialOutScansVO.VBATCHCODE.name];
		}
		if(scaninfo[MaterialOutScansVO.VSERIALCODE.name] != "") {
			row["vserialcode"] = scaninfo[MaterialOutScansVO.VSERIALCODE.name];
		}
		row["scannum"] = scaninfo[MaterialOutScansVO.SCANNUM.name];
		row["scanassistnum"] = scaninfo[MaterialOutVO.SCANASSISTNUM.name];
		//		$alert("row=" + $jsonToString(row));
		//根据计量单位转换数量属性的小数位数
		var retData = NCMMMOUtil.changeDecimalFiguresByMeascdoc(MaterialOutVO, [row]);
//		$alert("show retData=" + $jsonToString(retData));
		$ctx.push(retData[0]);
	}

	//新增或更新本地表记录
	//outvo: 上游单据vo
	//scaninfo： 扫描数据
	//rowid： null - 更新
	function updateLocalTableRecord(outvo, scaninfo, rowid) {
		var scanvo = {};
		//		$alert("scaninfo="+$jsonToString(scaninfo));
		if(rowid == null) {
			scanvo = createNewScanVO(outvo, scaninfo);
			scanvo[MaterialOutScansVO.ID.name] = "null";
		} else {
			scanvo = getScanVOByRowid(rowid);
			if(scanvo)
				scanvo = refreshScanvo(scanvo, scaninfo);
		}
//				$alert("scanvo before insert = " + $jsonToString(scanvo));
		//更新扫描表记录（新增or更新）
		updateScanRecord(scanvo, rowid);
		//更新上游单据表记录
		var vbillcode = outvo[MaterialOutVO.VBILLCODE.name];
		var crowno = outvo[MaterialOutVO.CROWNO.name];
		NCMMMOUtil.updateMaterialOutRecord(vbillcode, crowno);

	}

	//根据上游单据行vo和扫描记录组装一个vo变量
	function createNewScanVO(outvo, scaninfo) {
		var newscanvo = {};
		var columns = MaterialOutScansVO.prototype.getAllAttrs();
		Array.prototype.map.call(columns, function(col, i, arr) {
			if(outvo[col.name] != null) {
				newscanvo[col.name] = outvo[col.name];
			}
		});

		scaninfo[MaterialOutScansVO.SCANDATE.name] = NCMMPubUtil.getNowDateTime();
		scaninfo[MaterialOutScansVO.TS.name] = NCMMPubUtil.getTS();

		columns = MaterialOutScansVO.prototype.getAllAttrs();
		Array.prototype.map.call(columns, function(col, i, arr) {
			if(scaninfo[col.name] != null && scaninfo[col.name] != "") {
				newscanvo[col.name] = scaninfo[col.name];
			}
		});

		return newscanvo;
	}

	//根据rowid获得scanvo
	function getScanVOByRowid(rowid) {
		if(rowid == null)
			return null;
		var wheresql = "where rowid = " + rowid;
		var scanvos = NCMMPubUtil.queryVONoCallback(MaterialOutScansVO, wheresql);
//		scanvos = eval(scanvos);
		scanvos = NCMMPubUtil.htmlspecialjsonarray2UI(scanvos);
		if(scanvos != null) {
			var scanvo = scanvos[0];
			return scanvo;
		} else {
			return null;
		}
	}

	//用扫描记录更新表vo
	function refreshScanvo(scanvo, scaninfo) {
		var columns = MaterialOutScansVO.prototype.getAllAttrs();
		Array.prototype.map.call(columns, function(col, i, arr) {
			if(scaninfo[col.name] != null) {
				scanvo[col.name] = scaninfo[col.name];
			}
		});

		return scanvo;
	}

	//更新扫描记录表记录（rowid为null-新增， 否则-更新）
	function updateScanRecord(scanvo, rowid) {
		if(rowid == null) { //新增
			//			$alert("insert new scanvo");
			NCMMPubUtil.createTableWithAutoPK(MaterialOutScansVO);
			NCMMPubUtil.insertVO(MaterialOutScansVO, scanvo);
			rowid = NCMMMOUtil.getMaxRowid();
			//把新记录的rowid保存到ctx			
			$ctx.put("tablerowid", rowid);
			$ctx.dataBind();
			//			$alert("new tablerowid=" + rowid);
		} else {
			NCMMPubUtil.updateVOWithOutPK(MaterialOutScansVO, scanvo, rowid);
			$ctx.put("tablerowid", rowid);
			$ctx.dataBind();
		}
	}

	//提交按钮单击事件
	function onOneScanSubmit(sender, args) {
		//提交前先保存一下界面上的数据
		var ret = localSave(sender, args, true);
		if(ret == false)
			return;

		var rowid = $ctx.getString("tablerowid");
		if(rowid == null || rowid == "") {
			$alert("无法获取当前扫描记录!");
			return null;
		}
		//获得当前扫描记录vo
		var scanvo = getScanVOByRowid(rowid);
		if(scanvo == null) {
			$alert("无法获取当前扫描记录!");
			return null;
		}
		//获取当前扫描记录对应的上游单据vo
		var outvo = NCMMMOUtil.getOriginalOutvo(scanvo[MaterialOutScansVO.VBILLCODE.name], scanvo[MaterialOutVO.CROWNO.name]);
		if(outvo == null) {
			$alert("无法获提交当前扫描记录!");
			return null;
		}

		//组装提交数据
		var billinfos = NCMMMOUtil.getSubmitData(outvo, scanvo);
		if(billinfos == null)
			return;

		//提交数据到NC
		NCMMMOUtil.submitInfo2NC(billinfos, outvo, null);
	}

	function onBatchcodeInput(sender, args) {
		g_bNeedConfirm = true;
	}

	com.yonyou.ncmm_pac_pda.MaterialOutScanController.prototype = {
		imagebutton0_onclick: com$yonyou$ncmm_pac_pda$MaterialOutScanController$imagebutton0_onclick,
		load: com$yonyou$ncmm_pac_pda$MaterialOutScanController$load,
		initialize: com$yonyou$ncmm_pac_pda$MaterialOutScanController$initialize,
		evaljs: com$yonyou$ncmm_pac_pda$MaterialOutScanController$evaljs
	};
	com.yonyou.ncmm_pac_pda.MaterialOutScanController.registerClass('com.yonyou.ncmm_pac_pda.MaterialOutScanController', UMP.UI.Mvc.Controller);
} catch(e) {
	$e(e);
}